<script setup lang="ts">
import { FillBusinessForm, FillBusinessVO, FillDTO } from '@/api/fill/business/Types';
import { TableEnum } from '@/enums/business/TableEnum';
import {
  getFillActBusinessDetail,
  getListBusiness,
  getListBusinessAll,
  saveOrUpdateNew,
  submitAll,
  getInfo,
  getListIssueAll
} from '@/api/fill/business';
import { ref } from 'vue';
import { getYear } from '@/hooks/useDate';
import { FillActFrom } from '@/api/fill/management/Types';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import { startWorkFlow } from '@/api/workflow/task';
import { titleList, defaultYard, defaultDeptName } from '@/hooks/useCommon';
import { getTotal, getOldValue, highlightClass, getFillDesc, useTableHeight } from "@/hooks/useMethod";
import { format } from 'date-fns';
import IssuedDataDrawer from '@/components/IssuedDataDrawer/index.vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(true);
const showSearch = ref(true);
const { yard_type } = toRefs<any>(proxy?.useDict('yard_type'));
// 填报弹窗按钮开关
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const dialogIssue = reactive<DialogOption>({
  visible: false,
  title: ''
});

const fillOut = () => {
  if (!queryParams.value.deptCode) {
    proxy?.$modal.msgError('暂无预算部门，不能填报！');
    return;
  }
  dialog.visible = true;
  dialog.title = '填报';
  getBusinessFillList();
};
//切换的标签
const yardType = ref(defaultYard);
const queryFormRef = ref<ElFormInstance>();

// 查询参数
const queryParams = ref<FillDTO>({
  year: getYear(),
  yardCode: yardType.value,
  deptCode: undefined,
  id: undefined, //当前流程的主表id
  issue: undefined, //发布状态
  type: 1
});

const deptNameShow = ref(defaultDeptName);

// 初始化一个空的响应式数组 tableList，用于存储表格数据
const tableList = ref([]);

const tableIssueList = ref([]);
//重置表单,和当前流程id
const reset = () => {
  type.value = 1;
  submitButtonShow.value = true;
  queryParams.value.id = undefined;
  form.value = null;
};
const type = ref(1);
//全部列表查询
const getListAll = async (routeParams?: any) => {
  loading.value = true;
  if (routeParams) {
    //从流程那边跳过来，查询业务主表详情
    type.value = 2;
    await getFillActBusinessDetail(routeParams.id)
      .then((res) => {
        deptNameShow.value = res.data.deptName;
        queryParams.value.year = format(new Date(res.data.year + '-01-01'), 'yyyy');
        queryParams.value.deptCode = res.data.deptCode;
        form.value = res.data;
        queryParams.value.id = res.data.id;
      })
      .then(() => {
        getListBusinessAll(queryParams.value).then((res) => {
          tableList.value = res.data;
        });
      })
      .finally(() => {
        loading.value = false;
      });
    return;
  }
  // 业务填报过来
  reset();
  //获得用户信息和提交表单信息
  getInfo(queryParams.value)
    .then((res) => {
      let user = res.data.user;
      queryParams.value.deptCode = user.budgetDeptCode;
      deptNameShow.value = user.budgetDeptName;
      const actBusinessForm = res.data.actBusinessForm;
      if (actBusinessForm) {
        //已经提交过的
        form.value = actBusinessForm;
        //此流程为当前活跃的最新流程id
        queryParams.value.id = actBusinessForm.id;
        // 对于填写的人来说，只有审核中，已完成的不可以提交
        if (form.value.status === 'waiting' || form.value.status === 'finish') {
          submitButtonShow.value = false;
        }
      }
    })
    .then(() => {
      // console.log('business-form:', form.value);
      // console.log("business-submitButtonShow:", submitButtonShow.value);
      // 获取所有列表业务数据
      // 参数: queryParams.value - 查询参数，用于筛选获取列表数据的条件
      getListBusinessAll(queryParams.value).then((res) => {
        // 将获取到的列表数据赋值给 tableList.value
        tableList.value = res.data;
      });
    })
    .finally(() => {
      loading.value = false;
    });
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getListAll();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value.year = getYear();
  handleQuery();
};

const buttonLoading = ref(false);
/**-------------------------------弹窗填报----------------------------------------------*/
//选择的院区标签
const selectTab = (val: string) => {
  yardType.value = val;
  queryParams.value.yardCode = val;
  getBusinessFillList();
};

//列表数据
const list = ref<FillBusinessVO[]>([]);

//列表
const getBusinessFillList = async () => {
  await getListBusiness(queryParams.value)
    .then((res) => {
      list.value = res.data;
    })
    .finally(() => (loading.value = false));
};

// 初始化一个用于填充业务表单的响应式对象
const fillForm = ref<FillBusinessForm>({
  deptCode: undefined, // 预算部门代码
  deptName: undefined, // 部门名称
  yardCode: undefined, // 院区编码
  year: undefined, // 年份
  list: [] // 列表，填报的业务表单相关的各项数据条目
});

// 初始化一个名为noShow的响应式引用，用于控制元素的显示状态
const noShow = ref(false);

//赋值
const assignment = () => {
  const value = queryParams.value;
  fillForm.value.deptCode = value.deptCode;
  fillForm.value.yardCode = value.yardCode;
  fillForm.value.year = value.year;
  fillForm.value.deptName = deptNameShow.value;
};

//保存数据
const submitData = async (type: number) => {
  //校验科目是否为空
  if (list.value.length === 0) {
    proxy?.$modal.msgError('预算科目为空，请前往预算管理进行科目设置');
  }
  buttonLoading.value = true;
  if (type === 2) {
    noShow.value = true;
    buttonLoading.value = false;
  } else {
    noShow.value = false;
    fillForm.value.list = list.value;
    //赋值
    assignment();
    // 提交数据，可以通过 API 请求发送数据
    await saveOrUpdateNew(fillForm.value)
      .then((res) => {
        // 返回的当前流程id
        queryParams.value.id = res.data;
        proxy?.$modal.msgSuccess('保存成功');
      })
      .then(() => {
        // 重新加载数据
        getBusinessFillList();
      })
      .finally(() => (buttonLoading.value = false));
  }
};
//取消
const cancelClick = () => {
  dialog.visible = false;
  noShow.value = false;
  getListAll();
};

const cancelClickIssue = () => {
  dialogIssue.visible = false;
};
const openClickIssue = () => {
  dialogIssue.title = '';
  dialogIssue.visible = true;
  loading.value = true;
  getListIssueAll(queryParams.value)
    .then((res) => {
      tableIssueList.value = res.data;
    })
    .finally(() => (loading.value = false));
};

/**--------------------------------------审批流集成-----------------------------------------------*/
const form = ref<FillActFrom>({
  id: undefined,
  deptCode: undefined,
  deptName: undefined,
  status: undefined,
  year: undefined
});

//提交审核
const submit = async () => {
  if (!queryParams.value.deptCode) {
    proxy?.$modal.msgError('暂无预算部门，不能提交！');
    return;
  }
  form.value.year = queryParams.value.year;
  form.value.deptCode = queryParams.value.deptCode;
  form.value.deptName = deptNameShow.value;
  buttonLoading.value = true;

  submitAll(form.value)
    .then((res) => {
      form.value = res.data;
      handleStartWorkFlow(res.data);
    })
    .finally(() => (buttonLoading.value = false));
};
//路由参数
const routeParams = ref<Record<string, any>>({});
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const submitFormData = ref<StartProcessBo>({
  businessKey: '',
  tableName: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});
//提交申请
const handleStartWorkFlow = async (data: FillActFrom) => {
  try {
    //业务填报
    submitFormData.value.tableName = TableEnum.FILL_ACT_BUSINESS;
    submitFormData.value.businessKey = data.id;
    //流程变量
    taskVariables.value = {
      entity: data,
      purchaseDeptName: '/',
      deptName: data.deptName,
      userList: [1, 3],
      userList2: [1, 3]
    };
    submitFormData.value.variables = taskVariables.value;
    await startWorkFlow(submitFormData.value).then((res) => {
      if (submitVerifyRef.value) {
        buttonLoading.value = false;
        submitVerifyRef.value.openDialog(res.data.taskId);
      }
    });
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  if (type.value === 2) {
    //审批页面关闭页签
    await proxy.$tab.closePage(proxy.$route);
    proxy.$router.go(-1);
  } else {
    //填报页刷新列表
    await getListAll();
  }
};

//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

//校验提交按钮是否显示
const submitButtonShow = ref(true);

// //校验审批按钮是否显示
const approvalButtonShow = computed(() => {
  return routeParams.value.type === 'approval' && form.value.status && form.value.status === 'waiting';
});

//年份禁用
const show = ref(true);
onMounted(() => {

  nextTick(async () => {
    routeParams.value = proxy.$route.query;

    if (routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
      //禁用编辑
      submitButtonShow.value = false;
      show.value = false;
      await getListAll(routeParams.value);
    } else {
      show.value = true;
      await getListAll();
    }
  });
});

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'fill-business/export',
    {
      ...queryParams.value
    },
    `业务填报表.xlsx`
  );
};

// 使用示例
const tableStyle = useTableHeight(showSearch);
</script>

<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :inline="true">
            <el-form-item label="年份" prop="year">
              <el-date-picker type="year" format="YYYY" value-format="YYYY" v-model="queryParams.year" :disabled="!show" />
            </el-form-item>
            <el-form-item label="预算部门" prop="deptCode" label-width="120px">
              <el-input disabled :placeholder="deptNameShow" />
            </el-form-item>
            <el-form-item v-if="show">
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <div style="display: flex; justify-content: space-between">
          <div>
            <el-button type="primary" plain icon="EditPen" @click="fillOut()" v-hasPermi="['fill:business:add']" v-if="submitButtonShow">
              填报
            </el-button>
            <el-button
              type="success"
              plain
              icon="Position"
              v-hasPermi="['fill:business:submit']"
              :loading="buttonLoading"
              @click="submit()"
              v-if="submitButtonShow"
            >
              提交
            </el-button>
            <el-button v-if="approvalButtonShow" :loading="buttonLoading" type="primary" @click="approvalVerifyOpen" icon="Promotion">
              审批
            </el-button>
            <el-button
              v-if="form && form.id && form.status !== null && form.status !== 'draft'"
              type="primary"
              @click="handleApprovalRecord"
              icon="View"
            >
              流程进度
            </el-button>
            <el-button type="warning" plain icon="Download" @click="handleExport"> 导出</el-button>
            <el-button type="danger" plain icon="HelpFilled" @click="openClickIssue"> 查看下达数据</el-button>
            <span style="color: orangered; margin-left: 20px">【总计】：{{ getTotal(tableList) }} 万元</span>
          </div>

          <div v-if="show">
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getListAll" />
          </div>
        </div>
      </template>
      <div>
        <el-table ref="tableRef" :data="tableList" :style="tableStyle" :show-summary="true" append class="table-box-index enhanced-table">
          <el-table-column prop="subjectCode" label="预算科目编码" v-if="false" align="center" />
          <el-table-column prop="subjectName" label="预算科目名称" width="250" align="center" fixed="left" show-overflow-tooltip>
<!--            <template #default="scope">-->
<!--              <el-tooltip effect="dark" placement="top" :content="scope.row.subjectCode">-->
<!--                <span>{{ scope.row.subjectName }}</span>-->
<!--              </el-tooltip>-->
<!--            </template>-->
          </el-table-column>
          <el-table-column v-for="item in titleList" :key="item.key" :label="item.label" align="center">
            <el-table-column
              v-for="dict in yard_type"
              :key="dict.value"
              :label="dict.label"
              :prop="dict.value + '_' + item.key"
              align="center"
              min-width="150"
            >
              <template #default="scope">
                <!-- 判断是否有备注 -->
                <el-popover
                  v-if="getFillDesc(scope.row, dict.value, item.key) !== '无'"
                  :effect="'dark'"
                  placement="top"
                  :width="150"
                  trigger="hover"
                  :content="scope.row[dict.value + '_' + item.key + 'Desc']"
                >
                  <template #reference>
                    <span>{{ scope.row[dict.value + '_' + item.key] }}</span>
                  </template>
                </el-popover>
                <!-- 无备注时直接显示内容 -->
                <span v-else>{{ scope.row[dict.value + '_' + item.key] }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="合计" align="center">
            <el-table-column
              v-for="dict in yard_type"
              :key="dict.value"
              :label="dict.label"
              :prop="dict.value + '_total'"
              align="center"
              show-overflow-tooltip
              min-width="160"
            >
              <template #default="scope">
                <span v-if="dict === yard_type[0]" style="color: #4876ff">{{ scope.row[dict.value + '_total'] }}</span>
                <span v-if="dict === yard_type[1]" style="color: #00bfff">{{ scope.row[dict.value + '_total'] }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="总合计" prop="total" show-overflow-tooltip min-width="170">
              <template #default="scope">
                <span style="color: #00FF00">{{ scope.row['total'] }}</span>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 提交组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />

    <!--  填报抽屉页-->
    <el-drawer v-model="dialog.visible" direction="ttb" :title="dialog.title" append-to-body size="100%" :with-header="false">
      <el-tabs v-model="yardType" class="demo-tabs" @tab-change="selectTab">
        <el-tab-pane v-for="dict in yard_type" :key="dict.value" :label="dict.label" :name="dict.value" />
        <el-card shadow="never">
          <template #header>
            <div style="display: flex; justify-content: space-between">
              <div>
                <el-button type="primary" icon="Lock" @click="submitData(1)"> 保 存</el-button>
                <el-button type="success" icon="Unlock" @click="submitData(2)"> 编 辑</el-button>
              </div>
              <div>
                <el-button type="danger" @click="cancelClick" icon="Close">关 闭</el-button>
              </div>
            </div>
          </template>

          <el-table border stripe v-loading="loading" :data="list" :highlight-current-row="true" :height="850" class="table-box enhanced-table">
            <el-table-column prop="subjectName" label="预算科目名称" align="center" show-overflow-tooltip width="200">
              <template #default="scope">
                <el-tooltip effect="dark" placement="top" :content="scope.row.subjectCode">
                  <span>{{ scope.row.subjectName }}</span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="第一季度" align="center">
              <el-table-column prop="first" label="金额" align="center">
                <template #default="scope">
                  <el-input-number v-model="scope.row.first" v-if="noShow" :min="0.0" :max="999999999.99" :controls="false" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="firstDesc" label="备注" align="center" :stripe="true" show-overflow-tooltip>
                <template #default="scope">
                  <el-input v-model="scope.row.firstDesc" type="textarea" class="input-common" v-if="noShow" show-word-limit></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="第二季度" align="center">
              <el-table-column prop="second" label="金额" align="center">
                <template #default="scope">
                  <el-input-number v-model="scope.row.second" v-if="noShow" :min="0.0" :max="999999999.99" :controls="false" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="secondDesc" label="备注" align="center" show-overflow-tooltip :stripe="true">
                <template #default="scope">
                  <el-input v-model="scope.row.secondDesc" type="textarea" class="input-common" v-if="noShow" show-word-limit></el-input>
                </template>
              </el-table-column>
            </el-table-column>

            <el-table-column label="第三季度" align="center">
              <el-table-column prop="third" label="金额" align="center" show-overflow-tooltip>
                <template #default="scope">
                  <el-input-number v-model="scope.row.third" v-if="noShow" :min="0.0" :max="999999999.99" :controls="false" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="thirdDesc" label="备注" align="center" show-overflow-tooltip :stripe="true">
                <template #default="scope">
                  <el-input v-model="scope.row.thirdDesc" type="textarea" class="input-common" v-if="noShow" show-word-limit></el-input>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="第四季度" align="center">
              <el-table-column prop="fourth" label="金额" align="center">
                <template #default="scope">
                  <el-input-number v-model="scope.row.fourth" v-if="noShow" :min="0.0" :max="999999999.99" :controls="false" style="width: 100%" />
                </template>
              </el-table-column>
              <el-table-column prop="fourthDesc" label="备注" align="center" show-overflow-tooltip :stripe="true">
                <template #default="scope">
                  <el-input v-model="scope.row.fourthDesc" type="textarea" class="input-common" v-if="noShow" show-word-limit></el-input>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tabs>
    </el-drawer>

    <!--  下达数据抽屉页 -->
    <IssuedDataDrawer
      v-model="dialogIssue.visible"
      title="业务下达列表"
      :table-data="tableIssueList"
      :title-list="titleList"
      :yard-type="yard_type"
      :loading="loading"
      :get-old-value="getOldValue"
      :highlight-class="highlightClass"
    />
    <div></div>
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/styles/common-style';

.table-container {
  height: calc(100vh - 120px); /* 根据页面布局调整 */
}

/* 固定合计行 */
:deep(.el-table__footer-wrapper) {
  position: sticky;
  bottom: 0;
  background: #fff;
  z-index: 1000;
  box-shadow: 0 -1px 8px rgba(0, 0, 0, 0.08);
}

/* 固定表头 */
:deep(.el-table__header-wrapper) {
  position: sticky;
  top: 0;
  z-index: 1001;
}

/* 调整滚动条位置 */
:deep(.el-table__body-wrapper) {
  scrollbar-width: thin;
  overflow-y: auto !important;
}
</style>
